package cn.javazd.auth.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import cn.javazd.auth.entity.SysPermission;
import cn.javazd.auth.entity.SysUser;
import cn.javazd.auth.service.SysPermissionService;
import cn.javazd.auth.service.SysUserService;
import lombok.AllArgsConstructor;

@AllArgsConstructor
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

	private final SysUserService sysUserService;

	private final SysPermissionService sysPermissionService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

		SysUser user = sysUserService.findUserByUsername(username);
		if (null == user) {
			throw new UsernameNotFoundException("username:  " + username + "is not exist!");
		}

		List<SysPermission> permissions = sysPermissionService.findPermissionByUserId(user.getId());
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		// 设置用户权限
		permissions.forEach(permission -> {
			authorities.add(new SimpleGrantedAuthority(permission.getEname()));
		});

		// 返回认证用户
		return new User(user.getUsername(), user.getPassword(), authorities);
	}

}
